const Record = require("../models/record");

// 获取所有列表 post record/list
exports.getRecord = async (req, res) => {
  try {
    const pageNum = parseInt(req.body.pageNum) || 1; // 默认页码为1
    const pageSize = parseInt(req.body.pageSize) || 10; // 默认每页10条数据
    const startIndex = (pageNum - 1) * pageSize;
    const endIndex = pageNum * pageSize;
    const { userId, dateTime, income, type, isWin } = req.body;
    // 创建查询条件
    const query = {};
    userId && (query.userId = userId);
    dateTime && (query.dateTime = dateTime);
    income && (query.income = income);
    type && (query.type = type);
    isWin && (query.isWin = isWin);
    const records = await Record.find(query);
    const result = records.slice(startIndex, endIndex);
    if (!req.body.userId) {
      res.status(401).json({
        success: false,
        code: 401,
        error: "无效token",
        message: "请重新登录",
      });
    } else {
      res.status(200).json({
        success: true,
        code: 200,
        data: {
          list: result,
        },
      });
    }
  } catch (err) {
    console.log("err", err);
    res.status(500).json({
      success: false,
      error: "Server Error",
    });
  }
};

// 新增
exports.createRecord = async (req, res) => {
  try {
    const records = await Record.create(req.body);
    res.status(200).json({
      success: true,
      code: 200,
    });
  } catch (err) {
    if (err.code === 11000) {
      return res.status(400).json({
        success: false,
        error: "Duplicate field value",
      });
    }
    res.status(400).json({
      success: false,
      error: err.message,
    });
  }
};

// 删除
exports.deleteRecord = async (req, res) => {
  try {
    // 查找并删除记录
    const { id } = req.params; // 从请求参数中获取 ID
    const deletedRecord = await Record.findByIdAndDelete(id);
    if (!deletedRecord) {
      return res.status(200).json({
        success: false,
        code: 200,
        error: "记录未找到",
        message: "无法删除，记录不存在",
      });
    }
    res.status(200).json({
      success: true,
      code: 200,
      message: "记录删除成功",
    });
  } catch (err) {
    console.error("删除操作出错:", err); // 打印错误信息
    res.status(500).json({
      success: false,
      error: "Server Error",
    });
  }
};

/**
 * 根据月份筛选数据
 * @param {Array} data - 原始数据数组
 * @param {string} month - 目标月份 (格式: "YYYY-MM")
 * @returns {Array} 过滤后的数据
 */
function filterDataByMonth(data, month) {
  return data.filter((item) => {
    const date = new Date(item.dateTime);
    const itemMonth = `${date.getFullYear()}-${String(
      date.getMonth() + 1
    ).padStart(2, "0")}`;
    return itemMonth === month;
  });
}

// 获取月日的收支
exports.getMonthRecord = async (req, res) => {
  try {
    // 查找并删除记录
    const { userId, dateMonth } = req.body; // 从请求参数中获取 ID
    const records = await Record.find({ userId });
    const list = dateMonth ? filterDataByMonth(records, dateMonth) : records;
    const monthTotal = list.reduce((v, i) => +i.income + v, 0);

    res.status(200).json({
      success: true,
      code: 200,
      data: {
        list,
        monthTotal,
      },
    });
  } catch (err) {
    console.error("删除操作出错:", err); // 打印错误信息
    res.status(500).json({
      success: false,
      error: "Server Error",
    });
  }
};

/**
 * 根据年份筛选数据
 * @param {Array} data - 原始数据数组
 * @param {string} year - 目标年份 (格式: "YYYY")
 * @returns {Array} 过滤后的数据
 */
function filterDataByYear(data, year) {
  return data.filter((item) => {
    const date = new Date(item.dateTime);
    const itemYear = date.getFullYear().toString();
    return itemYear === year;
  });
}

// 获取年月的收支
exports.getYearRecord = async (req, res) => {
  try {
    // 查找并删除记录
    const { userId, dateYear } = req.body; // 从请求参数中获取 ID
    const records = await Record.find({ userId });
    const list = dateYear ? filterDataByYear(records, dateYear) : records;
    const yearTotal = list.reduce((v, i) => +i.income + v, 0);

    res.status(200).json({
      success: true,
      code: 200,
      data: {
        list,
        yearTotal,
      },
    });
  } catch (err) {
    console.error("删除操作出错:", err); // 打印错误信息
    res.status(500).json({
      success: false,
      error: "Server Error",
    });
  }
};
